<template>
	<view :style="[AppSkinVar]">
		<e-loading-page :loading="loading||payLoading"   >
			<template #icon>
				<loader ></loader>
			</template>
		</e-loading-page>
		<Tabs v-model="receivingType"></Tabs>
		<view class="overflow-hidd e-m-b-20" :style="[addressStyle]">
			<order-address v-model:info="address" type="1" v-show="receivingType === 1"></order-address>
			<storeAddress
				:dateTime="today"
				v-model:address="address"
				:addText="info.deliverAddress"
				:beginTime="info.beginTime"
				:endingTime="info.endingTime"
				:primary="AppSkin.primary"
				v-show="receivingType === 2"
				@timeChange="timeChange"
				@navigation="navigation"
			></storeAddress>
		</view>
		<view class="bg-white e-p-l-20 e-p-r-20 nearby-preview-box">
			<GoodsItme
				:goodsKeys="goodsKeys"
				:info="item"
				:allowDel="false"
				imgSize="180rpx"
				textBoxSize="194rpx"
				iconSize="36"
				line="2"
				v-for="(item, index) in goodsList"
				:key="item.id"
				@numChange="numChange"
			></GoodsItme>
			<view class="e-p-t-30 e-p-b-40">
				<view class="e-flex e-flex-between">
					<text class="c-666">{{ $t('order.商品总价') }}</text>
					<text>{{ $unitEn }}{{ money }}</text>
				</view>
				<view class="e-flex e-flex-between e-m-t-34 e-m-b-20">
					<text class="c-666">{{ $t('order.运费') }}</text>
					<text class="c-red">+{{ $unitEn }}{{ receivingType === 1 ? info.orderFreight : 0 }}</text>
				</view>
				<view class="e-flex e-flex-between c-666 e-m-b-10" v-if="info.orderMoneyDis">
					<text>{{ $t('order.已优惠') }}</text>
					<text class="c-red">{{ $unitEn }}{{ info.orderMoneyDis }}</text>
				</view>
			</view>
			<view class="e-flex e-flex-end e-p-t-22 e-p-b-24">
				<text class="e-p-r-20">{{ $t('nearby.小计') }}</text>
				<text class="fw-600">{{ $unitEn }}{{ payMoney }}</text>
			</view>
		</view>

		<view class="e-m-t-20 e-p-30 e-flex bg-white nearby-preview-box">
			<text class="e-m-r-76 c-secondary">{{ $t('classify.订单备注') }}</text>
			<e-input style="z-index: 1" :placeholder="$t('classify.请填写备注信息')" border="none" v-model="remark"></e-input>
		</view>
		<pay-popup storeType="2" v-model:show="show" @close="show = false" @pay="pay"></pay-popup>
		<view class="nearby-preview__button bg-white">
			<view class="bg-primary c-white e-flex-xy-center" @tap="buy">
				<text>{{ $t('classify.去支付') }}</text>
			</view>
		</view>
		<card-valid-code-popup :show="cardValidCodePopupShow"  @cancel="handleCancelCardPay" @confirm="handleCardPay"></card-valid-code-popup>
	</view>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { getPayResult, postPreviewNearbyStoreGoodsOrder, postPurchaseNearbyStoreGoods, postEditStoreCart, getAddressList } from '@/common/request/api';
import type { OrderGoods } from '@/common/request/api';
import { useCurrentInstance, useNavigation } from '@/common/hooks';
import Tabs from './child/tabs.vue';
import GoodsItme from './child/goods-item.vue';
import storeAddress from './child/store-address.vue';
import CardValidCodePopup from '../../child/cardValidCodePopup.vue'
import { timeFormat, throttle, accAdd } from '@/common/utils';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { usePay } from '../../hooks/usePay';
import type { UniGlobalData } from '@/typings/uni';

import { PayType } from '@/env';

const props = defineProps({
	storeId: {
		type: String,
		required: true
	}
});

const ctx = useCurrentInstance();

const { payLoading, systemPay,checkCardPay,handleCardPay,
		handleCancelCardPay,cardValidCodePopupShow, getH5PayResult } = usePay();
const { openNavigation } = useNavigation();
const loading = ref(true);
const info = ref<OrderGoods>({
	orderMoney: 0,
	orderDeliveryfee: 0,
	orderMoneyPay: 0,
	orderMoneyDis: 0,
	orderMoneyCoupon: 0,
	orderMoneyDeduction: 0,
	orderFreight: 0,
	orderTitle: '',
	storeId: '',
	storeName: '',
	location: '',
	orderCost: 0,
	verifyCode: '',
	storeLogo: '',
	storeHasOwn: 1,
	deputys: []
});
const goodsList = computed(() => info.value?.deputys || []);
const navigation = () => {
	openNavigation({
		location: info.value.location.split(',') || [],
		title: info.value.storeName
	});
};
const money = computed(() =>
	goodsList.value.reduce((a, b) => {
		return accAdd(a, b.deputyMoneyPay);
	}, 0)
);
const payMoney = computed(() => {
	return accAdd(money.value, receivingType.value === 1 ? info.value.orderFreight || 0 : 0);
});

const goodsKeys = {
	image: 'commodityUrl',
	skuName: 'commoditySpecName',
	price: 'deputyMoney',
	name: 'commodityName',
	qry: 'commodityCount'
};
const today = ref('');
const tomorrow = ref('');

const receivingType = ref(2);
const address = ref();
const addressStyle = computed(() => {
	return {
		borderRadius: receivingType.value === 1 ? '0 20rpx 20rpx 20rpx' : '20rpx 0 20rpx 20rpx'
	};
});



const predictTime = ref('');
const remark = ref('');

const show = ref(false);

const getData = () => {
	let params = { storeId: props.storeId, receivedId: address.value?.id };
	postPreviewNearbyStoreGoodsOrder(params).then((res) => {
		loading.value = false;
		info.value = res.data.orderVos[0];
		today.value = res.today;
		tomorrow.value = res.tomorrow;
	});
};

getData();

watch(address, (v) => {
	v && getData();
});

const numChange = (basketCount: number, goods: OrderGoods['deputys'][0]) => {
	postEditStoreCart({
		skuId: goods.commoditySpecId,
		basketCount
	}).then((res) => {
		getData();
	});
};
const timeChange = (type: number, time: string) => {
	let dateTime = type === 1 ? today.value : tomorrow.value;
	predictTime.value = timeFormat(dateTime, 'yyyy-mm-dd ') + time;
};

const buy = () => {
	if (!address.value.id) {
		ctx.$toastApp(ctx.$t('classify.请先添加收货地址再支付'));
		return;
	}
	show.value = true;
};

// 支付
const pay = throttle(async function (payId: number, payword: string | undefined = undefined, payType: PayType,payName:string, payisDefault:string,bankId?:number) {
	let data = {
		storeId: props.storeId,
		remark: remark.value,
		receivedId: address.value.id!,
		payId,
		fromType: getApp<UniGlobalData>().globalData?.payFromType,
		receivingType: receivingType.value,
		predictTime: receivingType.value === 2 ? predictTime.value : '',
		payword,
		bankId
	};
	if(!bankId&&checkCardPay(payType,(cardId:number) => {
		pay(payId,payword, payType,payName,payisDefault,cardId)
	})){
		return 
	}
	uni.hideLoading();
	const res = await postPurchaseNearbyStoreGoods(data);
	payLoading.value = false
	try {
		await systemPay({
			payType,
			resolveData: res,
			api: getPayResult,
			storageKey: 'nearbyPaycode',
			payUrl: res.data,
			payParams: res.data,
			payMoney:payMoney.value,
			successUrl: (id:string) => `order/success?type=4&id=${id}`,
			errorUrl: (msg:string) => `order/error?msg=${msg}`,
			orderUrl: 'order/index?type=1'
		});
	} catch (e) {
		ctx.$goTo(`/pages/order/error?msg=${e}`);
	}
}, 1500);

onLoad(() => {
	getAddressList()
		.then((res) => {
			if (res.data.length) {
				address.value = res.data.find((item) => item.isDefaul === 1) || undefined;
			}
		})
		.finally(() => {
			getData();
		});
	// #ifdef HTML5 || PREVIEW
	getH5PayResult('order/success', 'payOrderId', getPayResult);
	// #endif
});


</script>
<style>
page {
	background: #f3f3f3;
	padding: 20rpx 20rpx 180rpx 20rpx;
}
</style>
<style lang="scss" scoped>
.nearby-preview-box {
	border-radius: 20rpx;
	overflow: hidden;
}

.nearby-preview__button {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	height: 140rpx;
	padding: 26rpx 40rpx 24rpx 40rpx;
	z-index: $z-index-normal;
	> view {
		height: 100%;
		border-radius: 46rpx;
	}
}
</style>
